<template>
  <el-dialog
    :title="type === 'add' ? '新增密钥' : '修改密钥'"
    :visible.sync="dialogVisible"
    width="30%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form :model="formData" :rules="rules" label-width="100px" ref="form">
      <el-form-item label="密钥描述" prop="myms">
        <el-input v-model="formData.myms" maxlength="300" show-word-limit />
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import myglService from "@/api/mygl";
export default {
  data() {
    return {
      // 是否显示弹窗
      dialogVisible: false,
      // 新增流程表单数据
      formData: {
        myms: "",
      },
      type: "add",
      currentRow: {},
      // 表单校验规则
      rules: {
        myms: [
          { required: true, message: "请输入密钥描述", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    // 打开弹窗
    openDialog(row) {
      this.currentRow = {};
      this.formData.myms = "";
      this.$refs.form?.resetFields();
      if (row) {
        this.type = "edit";
        this.currentRow = row;
        this.formData.myms = row.myms;
      } else {
        this.type = "add";
      }
      this.dialogVisible = true;
    },
    // 提交表单
    submit() {
      if (this.type == "edit") {
        this.updateMy();
      } else {
        this.addMy();
      }
    },
    // 新增密钥
    addMy() {
      this.$refs.form?.validate((valid) => {
        if (valid) {
          myglService
            .addMy(this.formData)
            .then(() => {
              this.$emit("updateTable");
              this.$message({ type: "success", message: "新增成功!" });
              this.dialogVisible = false;
            })
            .catch((err) => {
              !err.isError &&
                this.$message({ type: "warning", message: err.message });
            });
        }
      });
    },
    // 修改密钥
    updateMy() {
      const params = {
        ak: this.currentRow.ak,
        myms: this.formData.myms,
      };
      myglService
        .updateMy(params)
        .then((res) => {
          this.$emit("updateTable");
          this.$message({ type: "success", message: "修改成功!" });
          this.dialogVisible = false;
        })
        .catch((err) => {
          !err.isError &&
            this.$message({ type: "warning", message: err.message });
        });
    },
  },
};
</script>
<style lang="scss" scoped></style>
